<?php

/*
 * Copyright (C) 2012 ETPASS
 * Author:ZHY <ZhuHY, zhuhy@etpass.com>
 * Date:2012-8-21 
 * Encoding:UTF-8 
 * FileName:Flight_tool.class.php
 * Link:http://www.etpass.com
 */

/**
 * Description of Flight_tool
 *
 * @author e
 */
class FlightCommonTools {

	/**
	 * 截断三字码
	 * @param string $cityCode输入城市三字码
	 * @return string 处理后结果
	 */
	public static function check_cut_cityCode($cityCode){
		if(strlen($cityCode) != 3){
			return substr($cityCode,0,3);
		}else{
			return $cityCode;
		}
	}
	
	/**
	 * 处理北京和上海的三字码
	 * @param string $inCode 输入城市三字码
	 */
	public static function changeCityCode($inCode){
		$inCode = self::check_cut_cityCode(strtoupper($inCode));
		if(in_array($inCode, array("PEK","NAY","BJS"))){
			$code = "SSS";
		}elseif(in_array($inCode, array("PVG","SHA"))){
			$code = "BBB";
		}else{
			$code = $inCode;
		}
		return $code;
	}
	
	/**
	 * 根据三字码获取城市相关信息
	 * @param string $code 城市三字码
	 * @param string $type 类型：zh|airPort|en
	 */
	public static function getCityInfo($code,$type){
		if($type == 'zh'){
			return Flight_static::$AirPort[$code][0];
		}elseif($type == 'airPort'){
			return Flight_static::$AirPort[$code][1];
		}elseif($type == 'en'){
			return Flight_static::$AirPort[$code][2];
		}elseif($type == 'airPortShort'){
			return Flight_static::$AirPort[$code][3];
		}else{
			return '';
		}
	}
	
	/**
	 * 当城市三字码是"BBB"或"SSS"时，需要往接口传"BJS"或"SHA"
	 *
	 * @param string $cityCode 城市代码
	 * @return string 
	 */
	public static function revertCityCode($cityCode)
	{
		if($cityCode=="SSS")
		{
			$cityCode="BJS";
		}
		else if($cityCode=="BBB")
		{
			$cityCode="SHA";
		}
	
		return $cityCode;
	}
        /*
	 * 生成临时随机ID,
	 */
	public static function createRandId()
	{
		return time().rand(1000, 9999);
	}
	/*
	 * 检测传入的ＩＤ是否合法
	 */
	public static function checkGetCacheId($num)
	{
		$re_str = FALSE;
		if ("" != $num && is_numeric($num))
		{	
			$new_num = substr($num,0,10);
			if (time()-$new_num<=3600)
			{
				$re_str = TRUE;
			}
		}
		return $re_str;
	}
        /*
	 * 对数据进行缓存处理
	 * mark_name 存入名
	 * c_data要进行缓存的数据
	 * handle_type操作类型，1为添加，2为读取,3为删除,4检测是否存在
	 * cache_time 缓存时间，默认为30分钟
	 */
	public static function cache_data($mark_name,$handle_type,$c_data="",$cache_time=1800)
	{
		//获取Memcached对象
		$cache = MemoryCache::getInstance();
		$re_str = "";
		switch ($handle_type) 
		{		
		//插入一笔数据
		 case "1":
			$re_str = $cache -> set($mark_name, $c_data, $cache_time);
			break;
			
		//从缓存中获取一笔数据
		 case "2":
		 	for ($i=0;;$i++)
		 	{
		 		$re_str = $cache -> get($mark_name);
				if ($re_str)
				{
					break;
				}
				if ($i>2)
				{
					break;
				}
		 	}
		 	if (empty($re_str))
		 	{
		 		$sql="SELECT cache_data FROM `memcache_backup` WHERE `cache_id` = '".$mark_name."' and `expired_time`>".time()." ORDER BY ID LIMIT 1";
				$_db=DB_MySQLi::getInstance(2);
				$re_db=$_db->getData_ASSOCS($sql);
				if(!empty($re_db))
				{
					$re_str =json_decode($re_db[0]["cache_data"],true);
				}
		 	}
			break;
		
		//删除一笔数据
		 case "3":
			//$re_str = $cache -> delete($mark_name);//外网服务器现在不支持删除功能
			break;
		
		//查看是否存在
		 case "4":
			$get_str = self::cache_data($mark_name,2);
			$re_str = !empty($get_str);
			break;
		}
		return $re_str;
	}
        	/**
	 * 将数据换成数组存入缓存,当保存失败时进行重复写入,并备份到数据库
	 * Enter description here ...
	 * @param unknown_type $unionID
	 */
	public static function save_to_memchche($cache_name,$cache_data,$max_num = 5)
	{
		$re_type = false;
                if(!is_array($cache_data))
                {
                    $cache_data = json_decode(json_encode($cache_data),true);
                }
		if (!empty($cache_name))
		{
			for ($i=1;$i<$max_num;$i++)
			{
                                self::cache_data($cache_name,"1",$cache_data);
				if (self::cache_data($cache_name,"4"))
				{
					$re_type =true;
					break;
				}
				
			}			
		}
		
		$_db=DB_MySQLi::getInstance();
		$re_db_type = $_db->query("INSERT INTO `memcache_backup`(`cache_id`,`cache_data`,`expired_time`)
						VALUES ('".$cache_name."','".$_db->escapeString(json_encode($cache_data))."', ".(time()+1800).")");
		if(!$re_type)
		{
			$error_meg = "Cache Name:".$cache_name;
			$error_meg .= "; \r\nCache Data:".json_encode($cache_data);
			$error_meg .= "; \r\nTO Database:".$re_db_type;
			$error_meg .= "; \r\nTo Cache:".$re_type;
			$error_meg .= "; \r\nCreate Date:".date("Y-m-d H:i:s");
			Log_File::writeFlightMemcacheLog($error_meg);
		}
		return ($re_type || $re_db_type);
	}

        /**
        *根据城市三字码和航空公司获取相关信息 
        * @return Array
        */
        public static function get_flight_city_info($city_code,$air_company,$time_str="")
        {
            $re_info = array();
            if("" !=$city_code && "" != $air_company)
            {
                $city_code = FlightCommonTools::check_cut_cityCode($city_code);
                $air_port_info = Flight_static::$AirPort[$city_code];

                $terminal_info = FlightCommonTools::get_terminal_info($city_code,$air_company);
                if("" != $time_str)
                {
                    $re_info["intTime"] = strtotime($time_str);
                }
                $re_info["cityName"] = $air_port_info[0];
                if($city_code != FlightCommonTools::changeCityCode($city_code))
                {
                    $re_info["cityName"] = Flight_static::$AirPort[FlightCommonTools::changeCityCode($city_code)][0];
                }
                $re_info["cityPinyin"] = $air_port_info[2];
                $re_info["airPortName"] = $air_port_info[1];
                $re_info["shortAirPortName"] = $air_port_info[3];

                $re_info["terminalName"] = $terminal_info[0];
                $re_info["terminalShortName"] = $terminal_info[1];

            }
            return $re_info;   
        }
        
        
        /**
         * 根据航空公司二字码获取航空公司信息
         */
        
        public static function get_airCompany_info($airCompany_code)
        {
            $re_arr = array();
            if("" != $airCompany_code && array_key_exists($airCompany_code,Flight_static::$AirCompany))
            {
                $re_arr["airCompanyCode"] = $airCompany_code;
                $re_arr["airCompanyName"] = Flight_static::$AirCompany[$airCompany_code];
                $re_arr["ShortAirCompany"] = Flight_static::$ShortAirCompany[$airCompany_code];
            }
            return $re_arr;
            
        }
        
        /**根据航空公司和城市三字码获取航站楼信息
        * 
         * @return Array
        */
        
        public static function get_terminal_info($city_code,$com_short_name)
        {
            $re_arr = array("1号航站楼","T1");
            if("" != $city_code && $com_short_name)
            {
                isset(FlightAirPortTerminal::$AirPortTerminal[$city_code][$com_short_name]) && $re_arr=FlightAirPortTerminal::$AirPortTerminal[$city_code][$com_short_name];
            }
            return $re_arr;
        }
        /*
	 * 格式化时间, 
	 */
	public static function generate_flight_time($data_str)
	{
            date_default_timezone_get('Asia/Chongqing');
            return date("c",strtotime($data_str));
	}
        /*
	 * 计算折扣
	 */
	public static function get_discount($base_price,$ticket_price)
	{
            $re_info = 0;
            if (0 != (int)$ticket_price && 0 != (int)$base_price)
            {
                    $re_info = round((int)$ticket_price/(int)$base_price*100);
            }
            return $re_info;
	}
       /*
	 * 根据成人预订的舱位信息获取儿童舱位信息
	 */
	public static function get_children_cabin($ad_cabin) {
            if ("F" == $ad_cabin || "C" == $ad_cabin) {
                return $ad_cabin;
            } else {
                return "Y";
            }
        }

        /**
         *将处理后的信息输出到页面
         * @param type $c_type 1成功，2变价，3重复订单，4系统错误，5页面跳转
         * @param type $jump_str 
         */
	public function echo_info($c_type,$jump_str="")
	{
		echo $c_type.$jump_str;
		exit;
	}
//        /**
//         *获取订单信息页
//         * @return string 
//         */
//        public static function Get_orderInfo()
//	{
//		$re_arr = array();
//		$re_arr["order_ID"] = $this->cache_id;		
//			$order_meg = Flight_interface::getOrderInfos($this->cache_id);
//			if (!is_null($order_meg))
//			{
//				$orderTicket_info=Handler_tool::dataTranslation($order_meg->OrderTicket);
//				$orderScore_info=Handler_tool::dataTranslation($order_meg->OrderScore);
//				$OrderFlightInfos = Handler_tool::dataTranslation($order_meg->OrderFlightInfos);
//				$this->is_same_userid($OrderFlightInfos[0]["T_id"]);
//				$re_arr["pirce"]	=$orderTicket_info[0]["paid_price"];
//				$re_arr["sace"]		=$orderTicket_info[0]["get_score"];
//				$re_arr["flight_meg_arr"] = $OrderFlightInfos[0]["dep_airport"]." - ".$OrderFlightInfos[0]["des_airport"];
//				$this->union_ID = $orderTicket_info[0]["Union_Member_ID"];
//				if ("1" != $orderTicket_info[0]["Sail_Type"] && isset($OrderFlightInfos[1]["des_airport"]))
//				{
//					$re_arr["flight_meg_arr"].=" - ".$OrderFlightInfos[1]["des_airport"];
//				}
//                                $this->ticketdelivery_info = Flight_common::get_uid_paytype($orderTicket_info[0]["Union_Member_ID"],"PayType");
//			}
//			else
//			{
//				$this->echo_return("订单不存在",HTTPURL."/member/");
//				exit;
//			}
//		
//
//
//		
//		return $re_arr;
//	}
        /**
         *验证银行ID是否可用
         * @param type $bank_id
         * @return boolean 
         */
        public static function check_bankid($bank_id)
        {
            $re_type = false;
            if ("" != $bank_id && (array_key_exists($bank_id, CashierStaticData::$EBank) || array_key_exists($bank_id, CashierStaticData::$ThirdPayment) || array_key_exists($bank_id, CashierStaticData::$CreditCardBank)))
            {
                $re_type = true;
            }
            return $re_type;
        } 
        
        	/*
	 * 根据传入的订单信息生成用于网银加密的ＫＥＹ
	 */
	public function generate_transaction_key($info_arr)
	{
		
		$re_str = 0;
		if (is_array($info_arr))
		{
                   //Source+BillNo+Channel+BankCode+TransType+Amount+ShowUrl+BackUrl+Ext+PayType+key
                    $primeval_str = $info_arr["Source"];
                    $primeval_str .= $info_arr["BillNo"];
                    $primeval_str .= $info_arr["Channel"];
                    $primeval_str .= $info_arr["BankCode"];
                    $primeval_str .= $info_arr["TransType"];
                    $primeval_str .= $info_arr["Amount"];
                    $primeval_str .= $info_arr["ShowUrl"];
                    $primeval_str .= $info_arr["BackUrl"];
                    $primeval_str .= $info_arr["Ext"];
                    $primeval_str .= "10".ORDER_PAY_KEY;
                    $re_str = md5($primeval_str);
		}
		return $re_str;
		
	}
        /*
	 * 根据传入的信息生成用于查询支付记录加密的ＫＥＹ
	 */
	public function generate_details_key($info_arr)
	{
		
		$re_str = 0;
		if (is_array($info_arr))
		{
                   //Source+BillNo+key
                    $primeval_str = $info_arr["Source"];
                    
                    if(empty($info_arr["TransNo"]))
                    {
                        $primeval_str .= $info_arr["BillNo"];
                    }
                    else
                    {
                        $primeval_str .= $info_arr["TransNo"];
                    }
                    $primeval_str .= ORDER_PAY_KEY;
                    $re_str = md5($primeval_str);
		}
		return $re_str;
		
	}
        /*
	 * 根据传入的订单信息生成用于信用卡的加密ＫＥＹ
	 */
	public function generate_transaction_creditcard_key($info_arr)
	{
		
		$re_str = 0;
		if (is_array($info_arr))
		{
                   //Source+BillNo+Channel+BankCode+TransType+Amount+BackUrl+Ext+CardNo+Cvv2+ExpiredDate+PayType+key
                    $primeval_str = $info_arr["Source"];
                    $primeval_str .= $info_arr["BillNo"];
                    $primeval_str .= $info_arr["Channel"];
                    $primeval_str .= $info_arr["BankCode"];
                    $primeval_str .= $info_arr["TransType"];
                    $primeval_str .= $info_arr["Amount"];
                    $primeval_str .= $info_arr["BackUrl"];
                    $primeval_str .= $info_arr["Ext"];
                    $primeval_str .= $info_arr["CardNo"];
                    $primeval_str .= $info_arr["Cvv2"];
                    $primeval_str .= $info_arr["ExpiredDate"];
                    $primeval_str .= "20".ORDER_PAY_KEY;
                    $re_str = md5($primeval_str);
                    
		}
		return $re_str;
		
	}
	
	/**
	 * 获取动态预订信息
	 * @param int $count	获取条数
	 * @return array
	 */
	public static function getOrderFlightNo($count){
		$cache = MemoryCache::getInstance();
		$flightLineAll = $cache ->get('flightLineFlightNo');
		if(empty($flightLineAll)){
			return array();
		}
		if(count($flightLineAll) < $count){
			$count = count($flightLineAll);
		}
		$flightLine = array_rand($flightLineAll,$count);
		$orderFlightNo = array();
		foreach($flightLine as $line){
			$orderFlightNoTemp = array();
			$orderFlightNoTemp['userId'] = sprintf("%03d", rand(000, 999));
			$orderFlightNoTemp['org'] = self::changeCityCode($flightLineAll[$line]['org']);
			$orderFlightNoTemp['dst'] = self::changeCityCode($flightLineAll[$line]['dst']);
			$orderFlightNoTemp['fromCity'] = Flight_static::$AirPort[$orderFlightNoTemp['org']][0];
			$orderFlightNoTemp['toCity'] = $orderFlightNoTemp['toCityShort'] = Flight_static::$AirPort[$orderFlightNoTemp['dst']][0];
			if(Handler_string::utf8_strlen($orderFlightNoTemp['fromCity'].$orderFlightNoTemp['toCity']) > 6){
				$count = 6-Handler_string::utf8_strlen($orderFlightNoTemp['fromCity']);
				$orderFlightNoTemp['toCityShort'] = Handler_string::utf8_substr($orderFlightNoTemp['toCity'],$count , '');
			}
			$orderFlightNoTemp['fromCityEn'] = Flight_static::$AirPort[$orderFlightNoTemp['org']][2];
			$orderFlightNoTemp['toCityEn'] = Flight_static::$AirPort[$orderFlightNoTemp['dst']][2];
			$flightNoKey = array_rand($flightLineAll[$line]['flightNo']);
			$orderFlightNoTemp['flightNo'] = $flightLineAll[$line]['flightNo'][$flightNoKey];
			$orderFlightNoTemp['airCompanyCode'] = substr($orderFlightNoTemp['flightNo'], 0,2);
			$orderFlightNoTemp['airCompanyName'] = Flight_static::$AirCompany[$orderFlightNoTemp['airCompanyCode']];
			$orderFlightNo[] = $orderFlightNoTemp;
		}
		return $orderFlightNo;
	}
	/**
	 * 根据A-Z获取到的城市列表
	 * @return array
	 */
	public static function get_city_by_ABC(){
		$cache = MemoryCache::getInstance();
		$city_arr = $cache->get('getCityByABC');
		if(!$city_arr){
			$city_arr = array();
			foreach (range('A','Z') as $value)
			{
				$re_arr = array();
				$special_city = array("NAY","PEK","PVG","SHA");
				foreach (Flight_static::$AirPort as $code => $airPort) {
					if ($value == strtoupper(substr($airPort[2],0,1)) && !in_array($code, $special_city))
					{
						$re_arr[] = array($airPort[2],$airPort[0]);
					}
				}
				if (!empty($re_arr))
				{
					$city_arr[$value] = $re_arr;
				}
			}
			$cache->set('getCityByABC', $city_arr, 86400);
		}
		return $city_arr;
	}
	
	/**
	 * 根据城市名、拼音、机场名获取相应的机场三字码
	 * @param string $key_str
	 * @param string $key_type:0为城市名，1为机场名，2为拼音
	 * @return string
	 */
	public static function get_airport_key($key_str,$key_type){
		$re_str = "";
		if (in_array($key_type, range(0,2)))
		{
			foreach (Flight_static::$AirPort as $key => $value) {
				if ($key_str == $value[$key_type])
				{
					$re_str = $key;
					break;
				}
			}
		}
		return $re_str;
	}
	
	/**
	 * 根据传入信息获取当前仓位的往返直降价格
	 *
	 * @param string $fromCode
	 * @param string $toCode
	 * @param string $airCompany
	 * @param string $cabin
	 * @param string $flightNo
	 * @param int $price
	 * @return int
	 */
	public static function getRoundTripPreferential($fromCode, $toCode, $airCompany, $cabin, $flightNo, $price, $BasePrice) {
		$roundTripPreferential = 0;
		$roundTripPreferentialConfig = Flight_static::$roundTripPreferential;
		$fromCode = self::changeCityCode ( $fromCode );
		$toCode = self::changeCityCode ( $toCode );
		$fromToCode = $fromCode . "_" . $toCode;
	
		$roundTripPreferential = self::getRoundTripPreferentialTemp($airCompany, $cabin, $flightNo, $price, $BasePrice, $roundTripPreferentialConfig['temp'], $fromToCode);
		if($roundTripPreferential != 0){
			return $roundTripPreferential;
		}
		if (array_key_exists ( $airCompany, $roundTripPreferentialConfig )) {
			$airComConfig = $roundTripPreferentialConfig [$airCompany];
			$isHasFlight = true;
			switch ($airComConfig ["line"] ["type"]) {
				case 'excludeFlight' :
					foreach ( $airComConfig ["line"] ["value"] as $excludeCabin ) {
						if (strpos ( $excludeCabin, "*" ) !== false) {
							$excludeCabinOne = str_replace ( "*", "", $excludeCabin );
							if (strpos ( $flightNo, $excludeCabinOne ) !== false) {
								$isHasFlight = false;
								break;
							}
						} else {
							if ($excludeCabin == $flightNo) {
								$isHasFlight = false;
								break;
							}
						}
					}
					break;
				case 'line' :
					if (!in_array ( $fromToCode, $airComConfig ["line"] ["value"] )) {
						$isHasFlight = false;
					}
					break;
				default :
					$isHasFlight = true;
					break;
			}
			if (in_array ( $cabin, $airComConfig ["cabin"] ) && $isHasFlight) {
				$roundTripPreferential = intval ( round ( $price * $airComConfig ["discount"], - 1 ) );
			}
		}
		return $roundTripPreferential;
	}
	
	/**
	 * 获取临时往返直降活动的数据
	 * @param string $airCompany
	 * @param string $cabin
	 * @param string $flightNo
	 * @param string $price
	 * @param string $BasePrice
	 * @param array  $roundTripPreferentialConfigTemp
	 * @param string $fromToCode
	 * @return number
	 */
	public static function getRoundTripPreferentialTemp($airCompany, $cabin, $flightNo, $price, $BasePrice, $roundTripPreferentialConfigTemp, $fromToCode){
		$nowDate = date("Y-m-d");
		$level = 0;
		foreach($roundTripPreferentialConfigTemp as $oneRoundTripPreferentialConfigTemp){
			if($oneRoundTripPreferentialConfigTemp["from"] <= $nowDate && $nowDate <= $oneRoundTripPreferentialConfigTemp["to"]){
				if(array_key_exists($airCompany, $oneRoundTripPreferentialConfigTemp)){
					if($level < $oneRoundTripPreferentialConfigTemp["level"]){
						$config = $oneRoundTripPreferentialConfigTemp[$airCompany];
						$level =  $oneRoundTripPreferentialConfigTemp["level"];
					}
				}
			}
		}
		if(isset($config)){
			switch ($config["key"]){
				case 'line':
					if(array_key_exists($fromToCode, $config["line"])){
						if(in_array($flightNo, $config["line"][$fromToCode]["flightNo"]["from"])){
							if(in_array($cabin, $config["line"][$fromToCode]["cabin"])){
								return self::getRoundTripPreferentialTempPrice($config["discount"], $BasePrice);
							}
						}
					}
					break;
				case 'linePrice':
					if(in_array($fromToCode, $config["linePrice"])){
						if(in_array($cabin, $config["cabin"])){
							return self::getRoundTripPreferentialTempPrice($config["discount"], $price);
						}
					}
					break;
			}
		}
		return 0;
	}
	
	/**
	 * 获取临时往返直降活动的价格
	 * @param string $discount
	 * @param string $BasePrice
	 * @return number
	 */
	public static function getRoundTripPreferentialTempPrice($discount,$BasePrice){
		switch($discount["type"]){
			case "Ybase":
				$price = intval ( round ( $BasePrice * $discount ["value"], 0 ) );
				break;
			case "price":
				$price = intval ( round ( $BasePrice * $discount ["value"], -1 ) );
				break;
		}
		return $price;
	}
	/**
	 * 是否符合空铁通赠送火车票规定
	 * @param string $fromCode		出发城市三字码
	 * @param string $toCode		到达城市三字码
	 * @param string $airCompany	航空公司二字码
	 * @param string $cabin			仓位代码
	 * @param string $date			起飞日期
	 * @return boolean				是否符合赠送火车票规定
	 */
	public static function getFlightTrainConfig($fromCode,$toCode,$airCompany,$cabin,$date){
		$flightTrainConfig = Flight_static::$flightTrainConfig;
		if(strtotime($date) - strtotime(date("Ymd")) >= 2*24*3600){
			if(in_array($fromCode, $flightTrainConfig['city']) || in_array($toCode, $flightTrainConfig['city'])){
				if(in_array($airCompany, $flightTrainConfig['airCompany']) && in_array($cabin, $flightTrainConfig['cabin'])){
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 是否符合空铁通赠送火车票规定(处理多航段)
	 * @param Array $flightInfo             航线数据
	 * @return boolean
	 */
	public static function isFlightSubway($flightInfo)
	{
		$time_now = time();
		$time_start = strtotime("08:00");
		$time_end = strtotime("17:30");
		if($time_now < $time_start || $time_now > $time_end){
			return false;
		}
		if(is_array($flightInfo)){
			foreach ($flightInfo as $flightValue) {
				if(FlightCommonTools::getFlightTrainConfig($flightValue["fromCode"], $flightValue["toCode"], $flightValue["airCompany"], $flightValue["cabin"], $flightValue["date"]))
				{
					return true;
				}
			}
		}
		return false;
	}
	/*
	 * 根据用户ＩＤ返回该用户保存过的乘客信息，并根据乘客的生日对乘客类型(成人，儿童，婴儿)进行修改
	*/
	public static function get_user_passengers_info($user_id,$flight_date)
	{
		$re_data = FlightDao::get_user_Member_info($user_id);
		if(!$re_data->resultCode)
		{
			$user_passengers = $re_data->dTContent;
			$user_passengers_arr = Handler_tool::dataTranslation($user_passengers);
			foreach ($user_passengers_arr as $value)
			{
				if (1 != $value["passengerType"])
				{
					$value["passengerType"] = Handler_tool::get_passenger_type_birthday($value["birthday"],$flight_date);
				}
				$re_arr[] = $value;
	
			}
			return $re_arr;
		}
		return "";
	}
}

?>
